const https = require('https')
const http = require('http')

const fs = require('fs')

const express = require('express')
const app = express()

const {connection} = require('./linkMySql')

function getMid1(url,data){
    /* app.get(`/${url}`,(req,res)=>{
        console.log(`/${url} 响应了`)
        res.send(JSON.parse(data))

    }) */
    fs.readFile(`./userInfo/${url}.txt`,(err,data)=>{
        if(err) throw err
        var da3 = JSON.parse(data)
        console.log(`getMid里的${url}.txt文件:`,da3,da3.data.mid)
    })
    app.get(`/${url}`,(req,res)=>{
        console.log(req.query)
        console.log(`/${url} 响应了`)
        res.send(JSON.parse(data))
    })
}

function getUserInfo1(uid){
    https.get(`https://api.bilibili.com/x/space/acc/info?mid=${uid}&jsonp=jsonp`,(res)=>{
        let data = ''
        res.on('data',(chunk)=>{
            data += chunk
        })
        res.on('end',()=>{
            // console.log(JSON.parse(data))

            console.log(JSON.parse(data))
            //下载图片
            // downloadUrl()

            //数据库访问
            /* connection.query('select * from bilibiliUserInfo_data',function(error, results, fields){
                if(error) throw error
                console.log('The solution is: ', results);
            }) */
            /* var insertOne = "insert into bilibiliUserInfo_data values(?,?,?,?)"
            var addInsertOne = []
            connection.query() */
            
            fileSave(data)
            
            var da2 = JSON.parse(data)
            console.log('data2:',da2.data.mid)//13805897
            getMid(da2.data.mid,data)
        })
    }).on('error',(err)=>{
        console.log("Erorr:",err.message)
    })

}

function fileSave(data){
    var da1 = JSON.parse(data)
    fs.stat(`./userInfo/${da1.data.mid}.json`,function (err,stat){
        if(stat&&stat.isFile()){
            //文件存在
            fs.readFile(`./userInfo/${da1.data.mid}.json`,(err,data)=>{
                if(err) throw err
                // console.log(data)
                // console.log(data.toString())
                // console.log(JSON.parse(data.toString()))
                var da = JSON.parse(data.toString())
                // console.log(da.data.name)//陈天羽----OK
                // console.log(da.data)
            })
        }else{
            //文件不存在
            // const data1 = new Uint8Array(Buffer.from(JSON.parse(data)))
            fs.writeFile(`./userInfo/${da1.data.mid}.json`,data,(err)=>{
                if(err) throw err
                userInfoImageWrite(da1.data)
                console.log('写入完成')
                
                insertMysql_bilibiliUserInfo_data(da1.data.mid,da1.data.name,da1.data.sex,da1.data.face)
            })
        }
    })
}
//http://i2.hdslb.com/bfs/face/ce2494fac2fd854dd2813b8960521d8e0d1a527c.jpg
//373943e434b10b0ec77ab4a51854688db6929716

const request = require('request')
/**
 * 读取链接中的image并下载
 * 请参考 https://www.php.cn/js-tutorial-387359.html
 * @param {*} data 获取用户全部信息
 */
let dataUrl;
async function userInfoImageWrite(data){
    let dataUrl1 = await data.face
    console.log('dataUrl--:',dataUrl1.slice(29))
    dataUrl = await dataUrl1.slice(29)
    await request(`${data.face}`).pipe(fs.createWriteStream(`./public/${dataUrl}`));
    return dataUrl;
}
/**
 * 
 * @param {*} data 参数的用户信息中的data
 */
async function userInfoImageRead(data){
    let readDataFace = await data.face
    let readImageBuffer = fs.createReadStream(`./public/${readDataFace.slice(29)}`,{highWaterMark:2})
    let imageImpl;
    //解决imageImpl += chunk乱码问题(一)
    // readImageBuffer.setEncoding('utf-8')
    //解决imageImpl += chunk乱码问题(二)
    var chunks = []
    var size=0;
    readImageBuffer.on('data',function(chunk){
        // imageImpl += chunk
        //解决imageImpl += chunk乱码问题(二)
        chunks.push(chunk)
        size += chunks.length;
    })
    readImageBuffer.on('end',function(){
        // console.log(imageImpl.toString())
        //解决imageImpl += chunk乱码问题(二)
        var buf=Buffer.concat(chunks,size);
        console.log('buf---',buf)
        // var str=iconv.decode(buf,'utf8');
        // console.log(str);
    })
    readImageBuffer.on('error',(err)=>{
        console.log(err)
    })
}
/**
 * 打开图片方法
 * 不能return得到数值，暂时舍弃，参考，请看这个文件所在的文件夹下的promiesTest.js文件
 * @param {*} data 
 */
function openReadImage(data){
    var imagePath;
    // const reader = await fs.createReadStream(`./public/${data.face.slice(29)}`,{highWaterMark:3});
    const reader = fs.createReadStream(`./public/${data.face.slice(29)}`,{start:0,end:20,highWaterMark:3});
    reader.on('data',(data)=>{
        console.log(data)
    })
    reader.on('open',()=>{
        console.log('文件已经打开',reader.pending)
    })
    reader.on('ready',()=>{
        console.log('数据已经准备好读取',reader.pending)
    })
    reader.on('close',async()=>{
        console.log('数据已读取')
        console.log('读取数据的路径' + reader.path)
        let pathPromise = new Promise((resolve,reject)=>{
            resolve(reader.path)
        }).then(res=>{
            console.log('res reader:',res)
            // console.log('this--',this)
            this.imagePath = res
        })
        imagePath = pathPromise.then(res=>{return res})
        console.log('imagePath:',imagePath)
        console.log('pathPromise:',pathPromise)
    })
    console.log('imagePath:',imagePath)
}

/**
 * 获取uid的本地图片路径(字符串)
 * @param {*} uid 
 * @returns 
 */
async function sendImage(uid){
    var dataAll;
    var dataImage;
    var dataImage1 = await new Promise((resolve,reject)=>{
        https.get(`https://api.bilibili.com/x/space/acc/info?mid=${uid}&jsonp=jsonp`,(res)=>{
            let data = ''
            res.on('data',(chunk)=>{
                data += chunk
            })
            res.on('end',()=>{
                console.log(JSON.parse(data))
                // console.log('dataMsg:',dataMsg)//var dataMsg = "我";  :我
                resolve(data)
            })
        }).on('error',(err)=>{
            console.log("Erorr:",err.message)
            reject(err.message)
        })
    }).then(res=>{
        console.log('sendImage function res:',res)
        dataAll = JSON.parse(res)
    })
    console.log('外dataAll:',dataAll)
    // return dataImage
    var read = await new Promise((resolve,reject)=>{
        const reader = fs.createReadStream(`./public/${dataAll.data.face.slice(29)}`,{highWaterMark:100});
        reader.on('data',(data)=>{
            console.log(data)
        })
        reader.on('open',()=>{
            console.log('文件已经打开',reader.pending)
        })
        reader.on('ready',()=>{
            console.log('数据已经准备好读取',reader.pending)
        })
        reader.on('close',()=>{
            console.log(reader.path)
            resolve(reader.path)
        })
    }).then(res=>{
        console.log(res)
        dataImage = res
    })
    console.log('dataImage:',dataImage)
    return dataImage
}

/**
 * 添加数据至数据
 * @param {*} mid   B站uid
 * @param {*} name  B站用户名
 * @param {*} sex   B站性别,是个枚举(有男,女,保密)
 * @param {*} face  B站头像http链接
 */
function insertMysql_bilibiliUserInfo_data(mid,name,sex,face){
    var insertOne = "insert into bilibiliUserInfo_data values(?,?,?,?)"
    var addInsertOne = [mid,name,sex,face]
    connection.query(insertOne,addInsertOne,function (err, result) {
        if(err){
        console.log('[INSERT ERROR] - ',err.message);
        return;
        }        

        console.log('--------------------------INSERT----------------------------');
        //console.log('INSERT ID:',result.insertId);        
        console.log('INSERT ID:',result);        
        console.log('-----------------------------------------------------------------\n\n');  
    })
}

/**
 * 主方法
 * @param {*} uid 传递mid实参的形参变量
 */
async function getUserInfo(uid){
    var dataMsg;
    var dataMsg1 = await new Promise((resolve,reject)=>{
        https.get(`https://api.bilibili.com/x/space/acc/info?mid=${uid}&jsonp=jsonp`,(res)=>{
            let data = ''
            res.on('data',(chunk)=>{
                data += chunk
            })
            res.on('end',()=>{
                console.log(JSON.parse(data))
                // console.log('dataMsg:',dataMsg)//var dataMsg = "我";  :我
                resolve(data)
                
            })
        }).on('error',(err)=>{
            console.log("Erorr:",err.message)
            reject(err.message)
        })
    }).then(res=>{
        console.log('promise then-res:',res)
        dataMsg = JSON.parse(res)
        fileSave(res)
    })
    console.log('dataMsg:',dataMsg)
    return dataMsg
}

/**
 * 获取直播间弹幕的全部信息
 * @param {*} roomid  直播间id
 * @returns 
 */
async function getLiveMsg(roomid){
    return await new Promise((resolve,reject)=>{
        https.get(`https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid=${roomid}`,(res)=>{
            let data = ''
            res.on('data',(chunk)=>{
                data += chunk
            })
            res.on('end',()=>{
                resolve(data)
            })
        }).on('error',(err)=>{
            reject(err.message)
        })
    }).then(async res=>{
        console.log(JSON.parse(res))
        return JSON.parse(res)
    })
}

async function writeLiveRoomMsg(data){
    fs.writeFile(`./live/${data}`,(data,err)=>{})
}

/**
 * 获取番剧的avid等
 */
//  let aid = 0;//aid
//  let bvid = "";//bvid号
//  let cid = 0;//cid
//  let fan_id = 0;//番剧的id
//  let link = "";//网络的链接
let HPMsg = {
    aid,bvid,cid,fan_id,link
}
async function getHisPlayMsg(ep_id){
    return new Promise((resolve,rehect)=>{
        https.get(`https://api.bilibili.com/pgc/view/web/season?ep_id=${ep_id}`,res=>{
            let data = "";
            res.on('data',chunk=>data += chunk);
            res.on('end',()=>{
                aid = data.result.episodes.aid;
                bvid = data.result.episodes.bvid;
                cid = data.result.episodes.cid;
                fan_id = data.result.episodes.id;
                link = data.result.episodes.link;
                resolve(JSON.parse(data));
            });
            res.on('error',(err)=>reject(err));
        });
    });
}
/**
 * 获取番剧的所有信息
 */
async function getHisPlay(avid,cid){}


module.exports = {
    getUserInfo,//获取用户数据
    fileSave,//保存用户信息到本地
    insertMysql_bilibiliUserInfo_data,//把数据存放到数据库中
    userInfoImageWrite,//获取用户名字到本地,参数的用户信息中的data
    userInfoImageRead,//存放ui用户face图片数据的字符串,参数的用户信息中的data
    openReadImage,//最终是为了获取到数据的路径
    sendImage,//获取图片路径的请求
    
    getLiveMsg,//获取直播间的弹幕信息

    HPMsg,//重要的aid等变量信息
    getHisPlayMsg,//获取番剧的avid等信息
}